package com.example.back.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.http.client.ClientHttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;

@Service
public class DeepSeekService {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekService.class);
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RestTemplate restTemplate;
    
    @Value("${deepseek.api.url}")
    private String apiUrl;
    
    @Value("${deepseek.api.key}")
    private String apiKey;
    
    @Value("${deepseek.api.model}")
    private String model;
    
    public DeepSeekService() {
        logger.info("Initializing DeepSeek service");
        this.restTemplate = new RestTemplate();
        // 禁用默认错误处理
        this.restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) {
                // 不做任何处理，让调用代码自己处理错误
            }
        });
    }
    
    @SuppressWarnings("unchecked")
    public String generateCode(String prompt) throws JsonProcessingException {
        logger.debug("Generating code with prompt: {}", prompt);
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", prompt);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            String jsonBody = objectMapper.writeValueAsString(requestBody);
            logger.info("Request body: {}", jsonBody);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            
            HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
            
            try {
                ResponseEntity<String> response = restTemplate.postForEntity(
                    apiUrl + "/chat/completions",
                    entity,
                    String.class
                );
                
                if (!response.getStatusCode().is2xxSuccessful()) {
                    throw new RuntimeException("SERVICE_ERROR");
                }
                
                String responseBody = response.getBody();
                if (responseBody == null) {
                    throw new RuntimeException("SERVICE_ERROR");
                }
                
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
                
                if (choices == null || choices.isEmpty()) {
                    throw new RuntimeException("SERVICE_ERROR");
                }
                
                Map<String, Object> choice = choices.get(0);
                Map<String, Object> message = (Map<String, Object>) choice.get("message");
                
                if (message == null || !message.containsKey("content")) {
                    throw new RuntimeException("SERVICE_ERROR");
                }
                
                return (String) message.get("content");
                
            } catch (ResourceAccessException e) {
                logger.error("API连接失败", e);
                throw new RuntimeException("SERVICE_UNAVAILABLE");
            } catch (Exception e) {
                logger.error("API调用失败", e);
                throw new RuntimeException("SERVICE_ERROR");
            }
        } catch (Exception e) {
            if (e.getMessage().equals("SERVICE_UNAVAILABLE") || 
                e.getMessage().equals("SERVICE_CONFIG_ERROR") ||
                e.getMessage().equals("SERVICE_ERROR")) {
                throw e;
            }
            logger.error("代码生成失败", e);
            throw new RuntimeException("SERVICE_ERROR");
        }
    }
} 